import React, { useRef, useState, useEffect, useContext } from 'react';
import { Layout, Table, Button, Spin, message, Input, Modal, Checkbox, Transfer } from 'antd';
import { ReloadOutlined, EditOutlined, LeftOutlined, RightOutlined, PlusOutlined } from '@ant-design/icons';
import { BsFileEarmarkCode } from 'react-icons/bs';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { TabsContext } from '../contexts/TabsContext';
import ProductDetail from './ProductDetail';

// 自定义样式
const customStyles = `
  .product-bom-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
    background: #fff;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  
  .horizontal-scroll-container {
    overflow-x: auto !important;
    overflow-y: hidden !important;
    display: block !important;
  }
  
  .ant-table-wrapper, .ant-table, .ant-table-container {
    min-width: 1200px !important;
  }
  
  /* 美化表格边框和表头 */
  .ant-table {
    border: 1px solid #e8e8e8 !important;
  }
  
  .ant-table-thead > tr > th {
    background-color: #f7f7f7 !important;
    font-weight: bold !important;
    border-bottom: 1px solid #e8e8e8 !important;
  }
  
  @media (max-width: 576px) {
    .product-bom-container {
      margin: 0;
      border-radius: 0;
    }
    
    .horizontal-scroll-container .ant-table-wrapper, 
    .horizontal-scroll-container .ant-table, 
    .horizontal-scroll-container .ant-table-container {
      min-width: 800px !important;
    }
    
    .ant-table-cell {
      padding: 4px !important;
      font-size: 12px !important;
    }
  }
  
  .bom-detail-item {
    display: grid;
    grid-template-columns: 120px 1fr;
    margin-bottom: 16px;
    align-items: center;
  }

  .bom-detail-label {
    color: #666;
    text-align: right;
    padding-right: 16px;
    font-weight: 500;
  }

  .bom-detail-value {
    color: #333;
    }
    
  .bom-detail-actions {
    display: flex;
    justify-content: flex-end;
    margin: 16px;
  }

  /* BOM详情页样式 */
  .bom-detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f0f2f5;
    overflow: auto;
  }

  .bom-detail-header {
    padding: 0;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    z-index: 1;
  }

  .bom-detail-tabs {
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid #e8e8e8;
  }

  .bom-detail-tab {
    padding: 16px 0;
    margin-right: 24px;
    cursor: pointer;
    position: relative;
    font-size: 14px;
  }

  .bom-detail-tab.active {
    color: #1766a3;
    font-weight: bold;
  }

  .bom-detail-tab.active::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 2px;
    background: #1766a3;
  }

  .bom-detail-content {
    padding: 24px;
    background: #fff;
    margin: 16px;
    flex: 1;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    overflow: auto;
  }

  .bom-detail-item {
    display: flex;
    margin-bottom: 16px;
  }

  .bom-detail-label {
    color: #666;
    text-align: right;
    padding-right: 16px;
    font-weight: 500;
    flex: 0 0 120px;
  }

  .bom-detail-value {
    color: #333;
    flex: 1;
  }

  .bom-detail-actions {
    display: flex;
    justify-content: flex-end;
    margin: 16px;
  }
  
  /* 响应式样式 */
  @media (max-width: 576px) {
    .bom-detail-content {
      padding: 16px;
      margin: 8px;
    }
    
    .bom-detail-label {
      flex: 0 0 100px;
    }
    
    .bom-detail-tab {
      padding: 12px 0;
      margin-right: 16px;
    }
  }
`;

const { Content } = Layout;

const ProductBOM = () => {
  // 使用TabsContext上下文
  const { addTab } = useContext(TabsContext);

  // 表格容器引用，用于横向滚动
  const tableContainerRef = useRef(null);
  
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [bomList, setBomList] = useState([]);
  const [productInfoMap, setProductInfoMap] = useState({});
  const [isMobile, setIsMobile] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取产品BOM列表
  const fetchProductBOMList = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_bom`, {
        params: {
          page,
          size: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        const items = response.data.data.items || [];
        
        // 处理返回的数据，确保所有必要字段都存在
        const processedItems = items.map(item => ({
          ...item,
          key: item.id,
          name: item.name || '未命名',
          code: item.code || '-',
          current_version: item.current_version || '-',
          create_time: item.create_time || null
        }));
        
        console.log('产品BOM列表数据:', processedItems);
        setBomList(processedItems);
        
        // 更新分页状态
        setPagination({
          ...pagination,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        setCurrentPage(page);
        
        // 收集所有的product_id，后续获取产品详情
        const productIds = processedItems.map(item => item.product_id).filter(id => id);
        if (productIds.length > 0) {
          fetchProductInfos(productIds);
        }
      } else {
        message.error('获取产品BOM列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品BOM列表错误:', error);
      message.error('获取产品BOM列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取产品详细信息
  const fetchProductInfos = async (productIds) => {
    try {
      // 创建一个临时的产品信息映射
      const tempProductInfoMap = { ...productInfoMap };
      
      // 并行获取每个产品的详细信息
      const promises = productIds.map(async (id) => {
        if (tempProductInfoMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
          if (response.data && response.data.code === 200) {
            tempProductInfoMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取产品 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新产品信息映射
      setProductInfoMap(tempProductInfoMap);
    } catch (error) {
      console.error('获取产品信息错误:', error);
    }
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchProductBOMList(page, pageSize);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        fetchProductBOMList(value, pageSize);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      const prevPage = currentPage - 1;
      setCurrentPage(prevPage);
      fetchProductBOMList(prevPage, pageSize);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchProductBOMList(nextPage, pageSize);
    }
  };

  // 打开BOM详情页签
  const openBOMDetail = (record) => {
    // 打开一个新的页签，用于展示BOM详情
    const tabKey = `bomDetail-${record.id}`;
    const tabTitle = `${record.code}`;
    addTab(tabKey, tabTitle, 'BOMDetail', { bomId: record.id, code: record.code });
  };

  // 打开产品详情
  const openProductDetail = (productId) => {
    if (!productId) return;
    
    // 获取产品信息
    const productInfo = productInfoMap[productId] || {};
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${productId}`;
    const tabTitle = `${productInfo.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId });
  };

  // 列定义
  const getTableColumns = () => {
    const baseColumns = [
      {
        title: 'BOM名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
            onClick={() => openBOMDetail(record)}
          >
            <BsFileEarmarkCode 
              style={{ 
                fontSize: isMobile ? '12px' : '16px', 
                marginRight: isMobile ? '4px' : '8px',
                color: '#1766a3'
              }} 
            />
            <span>{text}</span>
          </span>
        )
      },
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
            onClick={() => openBOMDetail(record)}
          >
            {text || '-'}
          </span>
        )
      },
      {
        title: '版本',
        dataIndex: 'current_version',
        key: 'current_version',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
            onClick={() => openBOMDetail(record)}
          >
            {text || '-'}
          </span>
        )
      }
    ];
    
    // 移动端显示核心列
    if (isMobile) {
      return baseColumns;
    }
    
    // 桌面端显示完整列
    return [
      ...baseColumns,
      {
        title: '产品名称',
        dataIndex: 'product_id',
        key: 'product_name',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.name || '-'}
            </span>
          );
        }
      },
      {
        title: '产品编码',
        dataIndex: 'product_id',
        key: 'product_code',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.code || '-'}
            </span>
          );
        }
      },
      {
        title: '产品类型',
        dataIndex: 'product_id',
        key: 'product_type',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{productInfo.product_type || '-'}</span>;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => {
          if (!text) return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>-</span>;
          try {
            const date = new Date(text);
            if (!isNaN(date.getTime())) {
              return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>
                {date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')}
              </span>;
            }
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text}</span>;
          } catch (error) {
            console.error('日期格式化错误:', error);
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>;
          }
        }
      }
    ];
  };

  // 根据数据行数确定行高
  const getRowClassName = () => {
    const dataLength = bomList.length;
    if (dataLength >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 组件挂载时加载数据
  useEffect(() => {
    fetchProductBOMList();
  }, []);

  // 刷新数据
  const handleRefresh = () => {
    fetchProductBOMList(pagination.current, pagination.pageSize);
  };

  return (
    <Layout className={`product-bom-container ${isMobile ? 'mobile-layout' : ''}`}>
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      <Content style={{ padding: '0', height: '100%' }}>
        <div style={{ 
          height: '100%',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {/* 标题栏 */}
          <div className="table-header-actions">
            <div style={{ 
              fontWeight: 'bold', 
              fontSize: isMobile ? '14px' : '18px',
              display: 'flex',
              alignItems: 'center',
              color: '#1766a3'
            }}>
              <BsFileEarmarkCode style={{ marginRight: '8px' }} />
              <span>产品BOM列表</span>
            </div>
            <div className="action-buttons">
            <Button 
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
              size={isMobile ? 'small' : 'middle'}
              title="刷新数据"
            >
              刷新
            </Button>
            </div>
          </div>
          
          {/* 表格容器 */}
          <div style={{ flex: 1, overflow: 'auto' }}>
            <div 
              ref={tableContainerRef}
              className="horizontal-scroll-container"
              data-rows-count={bomList.length > 10 ? "many" : "few"}
            >
                <Spin spinning={loading}>
                  <Table
                    className={`data-table ${bomList.length >= 10 || isMobile ? 'compact-table' : ''}`}
                    dataSource={bomList}
                    columns={getTableColumns()}
                    pagination={false}
                    rowClassName={getRowClassName}
                    size={isMobile || bomList.length >= 10 ? 'small' : 'middle'}
                    bordered={true}
                    scroll={{ x: bomList.length > 0 ? (isMobile ? 800 : 'max-content') : undefined }}
                    tableLayout="auto"
                    locale={{ emptyText: '暂无数据' }}
                  />
                </Spin>
              </div>
            </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
          </div>
          
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goPrevPage}
                disabled={currentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={inputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={currentPage}
                onChange={handlePageInputChange}
                onKeyPress={handlePageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goNextPage}
                disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {pageSize} / 页
                  </span>
            </div>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

// 产品BOM详情组件
const BOMDetail = ({ bomId }) => {
  const { addTab } = useContext(TabsContext);

  const [loading, setLoading] = useState(false);
  const [bomDetail, setBomDetail] = useState(null);
  const [activeTab, setActiveTab] = useState('detail');
  const [isMobile, setIsMobile] = useState(false);
  const [bomItems, setBomItems] = useState([]);
  const [productDetailsMap, setProductDetailsMap] = useState({});
  const [bomItemsLoading, setBomItemsLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);

  // 添加产品选择相关状态
  const [addItemModalVisible, setAddItemModalVisible] = useState(false);
  const [productSelectLoading, setProductSelectLoading] = useState(false);
  const [availableProducts, setAvailableProducts] = useState([]);
  const [selectedProductIds, setSelectedProductIds] = useState([]);
  const [isCreatingItems, setIsCreatingItems] = useState(false);
  
  // 添加编辑状态相关状态
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取产品BOM详情
  useEffect(() => {
    const fetchBOMDetail = async () => {
      if (!bomId) return;
      
      setLoading(true);
      try {
        const response = await axios.get(`${API_BASE_URL}/api/product_bom/${bomId}`);
        
        if (response.data && response.data.code === 200) {
          console.log('BOM详情数据:', response.data.data);
          setBomDetail(response.data.data);
        } else {
          message.error('获取BOM详情失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取BOM详情错误:', error);
        message.error('获取BOM详情失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchBOMDetail();
  }, [bomId]);

  // 获取产品BOM明细项列表
  const fetchBOMItems = async (page = 1, pageSize = 10) => {
    if (!bomId) return;
    
    setBomItemsLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_bom/${bomId}/items`, {
        params: {
          page,
          size: 10
        }
      });
      
      if (response.data && response.data.code === 200) {
        console.log('BOM明细项数据:', response.data.data);
        const items = response.data.data.items || [];
        setBomItems(items);
        setPagination({
          ...pagination,
          current: page,
          pageSize: 10,
          total: response.data.data.total || 0
        });
        
        // 收集所有的product_id，后续获取产品详情
        const productIds = items.map(item => item.product_id).filter(id => id);
        if (productIds.length > 0) {
          fetchProductDetails(productIds);
        }
      } else {
        message.error('获取BOM明细项失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取BOM明细项错误:', error);
      message.error('获取BOM明细项失败: ' + (error.message || '网络错误'));
    } finally {
      setBomItemsLoading(false);
    }
  };

  // 获取产品详情
  const fetchProductDetails = async (productIds) => {
    try {
      // 创建一个临时的产品信息映射
      const tempProductDetailsMap = { ...productDetailsMap };
      
      // 并行获取每个产品的详细信息
      const promises = productIds.map(async (id) => {
        if (tempProductDetailsMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
          if (response.data && response.data.code === 200) {
            tempProductDetailsMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取产品 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新产品信息映射
      setProductDetailsMap(tempProductDetailsMap);
    } catch (error) {
      console.error('获取产品信息错误:', error);
    }
  };

  // 处理选项卡切换
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    if (tab === 'list') {
      fetchBOMItems(pagination.current, pagination.pageSize);
    }
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    fetchBOMItems(pagination.current, pagination.pageSize);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        fetchBOMItems(value, pageSize);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      const prevPage = currentPage - 1;
      setCurrentPage(prevPage);
      fetchBOMItems(prevPage, pageSize);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchBOMItems(nextPage, pageSize);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    try {
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      }
      return dateString;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateString || '-';
    }
  };

  // 状态映射
  const getStatusText = (status) => {
    const statusMap = {
      'active': '生效',
      'inactive': '未生效',
      'draft': '草稿',
      'archived': '归档'
    };
    return statusMap[status] || status || '-';
  };

  // 打开产品详情
  const openProductDetail = (productId) => {
    if (!productId) return;
    
    // 获取产品信息
    const productInfo = productDetailsMap[productId] || {};
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${productId}`;
    const tabTitle = `${productInfo.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId });
  };

  // 获取BOM列表列定义
  const getBomItemColumns = () => {
    return [
      {
        title: '编码',
        dataIndex: 'product_id',
        key: 'code',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productDetailsMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.code || '-'}
            </span>
          );
        }
      },
      {
        title: '名称',
        dataIndex: 'product_id',
        key: 'name',
        align: 'left',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productDetailsMap[productId] || {};
          return (
            <span 
              style={{ cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.name || '-'}
            </span>
          );
        }
      },
      {
        title: '状态',
        dataIndex: 'product_id',
        key: 'status',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productDetailsMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{getStatusText(productInfo.status)}</span>;
        }
      },
      {
        title: '当前版本',
        dataIndex: 'product_id',
        key: 'current_version',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productDetailsMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{productInfo.current_version || '-'}</span>;
        }
      },
      {
        title: '类型',
        dataIndex: 'product_id',
        key: 'product_type',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productDetailsMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{productInfo.product_type || '-'}</span>;
        }
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '层级',
        dataIndex: 'item_level',
        key: 'item_level',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '父项ID',
        dataIndex: 'parent_item_id',
        key: 'parent_item_id',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      }
    ];
  };

  // 获取行样式
  const getRowClassName = () => {
    if (bomItems.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 渲染BOM详情内容
  const renderBOMDetail = () => {
    if (!bomDetail) {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          {loading ? '正在加载...' : '暂无数据'}
        </div>
      );
    }
    
    return (
      <div>
        <div className="bom-detail-item">
          <div className="bom-detail-label">编码:</div>
          <div className="bom-detail-value">{bomDetail.code || '-'}</div>
        </div>
        
        <div className="bom-detail-item">
          <div className="bom-detail-label">名称:</div>
          <div className="bom-detail-value">{bomDetail.name || '-'}</div>
        </div>
        
        <div className="bom-detail-item">
          <div className="bom-detail-label">当前版本:</div>
          <div className="bom-detail-value">{bomDetail.current_version || '-'}</div>
        </div>
        
        <div className="bom-detail-item">
          <div className="bom-detail-label">状态:</div>
          <div className="bom-detail-value">{getStatusText(bomDetail.status)}</div>
        </div>
        
        <div className="bom-detail-item">
          <div className="bom-detail-label">创建时间:</div>
          <div className="bom-detail-value">{formatDate(bomDetail.create_time)}</div>
        </div>
        
        <div className="bom-detail-item">
          <div className="bom-detail-label">更新时间:</div>
          <div className="bom-detail-value">{formatDate(bomDetail.update_time)}</div>
        </div>
      </div>
    );
  };

  // 渲染BOM明细列表
  const renderBOMList = () => {
    return (
      <div className="bom-list-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Spin spinning={bomItemsLoading}>
          {/* 添加按钮区域 */}
          <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end' }}>
            <Button 
              type="primary"
              icon={<PlusOutlined />}
              onClick={checkBOMStatus}
            >
              添加现有项
            </Button>
          </div>
          
          <div style={{ flex: 1, overflow: 'auto' }}>
            <Table
              className={`data-table ${bomItems.length >= 10 || isMobile ? 'compact-table' : ''}`}
              dataSource={bomItems}
              columns={getBomItemColumns()}
              pagination={false}
              rowClassName={getRowClassName}
              size={isMobile || bomItems.length >= 10 ? 'small' : 'middle'}
              bordered={true}
              scroll={{ x: isMobile ? 800 : 'max-content' }}
              tableLayout="auto"
              locale={{ emptyText: '暂无数据' }}
            />
          </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goPrevPage}
                disabled={currentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={inputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={currentPage}
                onChange={handlePageInputChange}
                onKeyPress={handlePageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goNextPage}
                disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {pageSize} / 页
              </span>
            </div>
          </div>
        </Spin>
        
        {/* 添加产品选择模态框 */}
        <Modal
          title="添加现有项"
          open={addItemModalVisible}
          onOk={handleAddItemConfirm}
          onCancel={handleAddItemCancel}
          width={700}
          confirmLoading={isCreatingItems}
          maskClosable={false}
        >
          <Spin spinning={productSelectLoading}>
            <div style={{ marginBottom: '16px' }}>
              请选择要添加到BOM的产品：
            </div>
            <Transfer
              dataSource={availableProducts}
              showSearch
              filterOption={(inputValue, item) => 
                item.title.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1 ||
                item.description.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1
              }
              targetKeys={selectedProductIds}
              onChange={handleProductSelectChange}
              titles={['可选产品', '已选产品']}
              listStyle={{
                width: 280,
                height: 400,
              }}
              render={item => `${item.title} - ${item.description}`}
            />
          </Spin>
        </Modal>
      </div>
    );
  };

  // 显示BOM状态提示弹窗
  const showBomStatusAlert = (status) => {
    console.log('尝试显示状态提示弹窗:', status);
    
    // 使用alert直接显示
    window.alert(`产品BOM已${status}不可编辑`);
    
    // 同时也尝试使用Modal
    try {
      Modal.error({
        title: '无法编辑',
        content: `产品BOM已${status}不可编辑`,
        okText: '我知道了'
      });
    } catch (err) {
      console.error('Modal显示错误:', err);
    }
  };

  // 检查BOM状态
  const checkBOMStatus = async () => {
    try {
      // 获取BOM详情
      const response = await axios.get(`${API_BASE_URL}/api/product_bom/${bomId}`);
      
      if (response.data && response.data.code === 200) {
        const bomData = response.data.data;
        console.log('BOM状态检查:', bomData);
        
        // 检查BOM状态是否为可编辑状态（草稿或draft）
        // 注意：API可能返回中文"草稿"或英文"draft"
        const status = bomData.status ? bomData.status.toLowerCase() : '';
        const isDraft = status === '草稿' || status === 'draft';
        
        console.log('BOM状态:', status, '是否为草稿:', isDraft);
        
        if (isDraft) {
          // 如果是草稿状态，可以继续添加项
          openAddItemModal();
        } else {
          // 如果不是草稿状态，使用自定义方法显示提示
          console.log('BOM状态不可编辑:', bomData.status);
          showBomStatusAlert(bomData.status);
        }
      } else {
        message.error('获取BOM状态失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('检查BOM状态错误:', error);
      message.error('检查BOM状态失败: ' + (error.message || '网络错误'));
    }
  };

  // 打开添加现有项模态框
  const openAddItemModal = async () => {
    setProductSelectLoading(true);
    
    try {
      // 获取所有产品列表
      const response = await axios.get(`${API_BASE_URL}/api/product_info`, {
        params: {
          page: 1,
          size: 100
        }
      });
      
      if (response.data && response.data.code === 200) {
        const products = response.data.data.items || [];
        // 转换为Transfer需要的格式
        const formattedProducts = products.map(product => ({
          key: product.id,
          title: `${product.name} (${product.code})`,
          description: product.product_type,
          code: product.code,
          product_type: product.product_type
        }));
        
        setAvailableProducts(formattedProducts);
        setAddItemModalVisible(true);
      } else {
        message.error('获取产品列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品列表错误:', error);
      message.error('获取产品列表失败: ' + (error.message || '网络错误'));
    } finally {
      setProductSelectLoading(false);
    }
  };

  // 处理选择产品变化
  const handleProductSelectChange = (selectedKeys) => {
    setSelectedProductIds(selectedKeys);
  };

  // 处理取消添加
  const handleAddItemCancel = () => {
    setAddItemModalVisible(false);
    setSelectedProductIds([]);
  };

  // 处理确认添加
  const handleAddItemConfirm = async () => {
    if (selectedProductIds.length === 0) {
      message.warning('请至少选择一个产品');
      return;
    }
    
    setIsCreatingItems(true);
    
    try {
      // 为每个选中的产品创建BOM项
      const creationPromises = selectedProductIds.map(productId => {
        // 创建BOM项的请求体
        const requestBody = {
          bom_id: bomId,
          product_id: parseInt(productId),
          quantity: 1,  // 默认数量为1
          unit: "个",   // 默认单位为"个"
          item_level: 1, // 默认层级为1
          parent_item_id: null // 默认没有父项
        };
        
        return axios.post(`${API_BASE_URL}/api/product_bom_item`, requestBody);
      });
      
      // 等待所有创建请求完成
      const results = await Promise.allSettled(creationPromises);
      
      // 统计成功和失败的数量
      const successCount = results.filter(result => result.status === 'fulfilled').length;
      const failCount = results.filter(result => result.status === 'rejected').length;
      
      if (successCount > 0) {
        message.success(`成功添加${successCount}个BOM项`);
        // 刷新BOM项列表
        fetchBOMItems(currentPage, pageSize);
      }
      
      if (failCount > 0) {
        message.warning(`${failCount}个BOM项添加失败`);
      }
      
      // 关闭模态框并清空选择
      setAddItemModalVisible(false);
      setSelectedProductIds([]);
    } catch (error) {
      console.error('创建BOM项错误:', error);
      message.error('创建BOM项失败: ' + (error.message || '网络错误'));
    } finally {
      setIsCreatingItems(false);
    }
  };

  // 检查BOM编辑状态
  const checkBOMEditStatus = async () => {
    try {
      // 获取BOM详情
      const response = await axios.get(`${API_BASE_URL}/api/product_bom/${bomId}`);
      
      if (response.data && response.data.code === 200) {
        const bomData = response.data.data;
        console.log('BOM编辑状态检查:', bomData);
        
        // 检查BOM状态是否为可编辑状态（草稿或draft）
        const status = bomData.status ? bomData.status.toLowerCase() : '';
        const isDraft = status === '草稿' || status === 'draft';
        
        console.log('BOM状态:', status, '是否为草稿:', isDraft);
        
        if (isDraft) {
          // 如果是草稿状态，显示编辑模态框
          setEditModalVisible(true);
        } else {
          // 如果不是草稿状态，显示提示
          console.log('BOM状态不可编辑:', bomData.status);
          showBomStatusAlert(bomData.status);
        }
      } else {
        message.error('获取BOM状态失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('检查BOM编辑状态错误:', error);
      message.error('检查BOM状态失败: ' + (error.message || '网络错误'));
    }
  };

  // 处理取消编辑
  const handleEditCancel = () => {
    setEditModalVisible(false);
  };

  // 处理确认编辑（修改状态为发布）
  const handleEditConfirm = async () => {
    try {
      setIsUpdatingStatus(true);
      
      // 更新BOM状态为发布
      const response = await axios.put(`${API_BASE_URL}/api/product_bom/${bomId}`, {
        status: '发布'  // 设置状态为发布
      });
      
      if (response.data && (response.data.code === 200 || response.data.code === 201)) {
        message.success('BOM状态已更新为发布');
        
        // 刷新BOM详情
        const refreshResponse = await axios.get(`${API_BASE_URL}/api/product_bom/${bomId}`);
        if (refreshResponse.data && refreshResponse.data.code === 200) {
          setBomDetail(refreshResponse.data.data);
        }
        
        // 关闭模态框
        setEditModalVisible(false);
      } else {
        message.error('更新BOM状态失败: ' + (response.data?.message || '未知错误'));
      }
    } catch (error) {
      console.error('更新BOM状态错误:', error);
      message.error('更新BOM状态失败: ' + (error.message || '网络错误'));
    } finally {
      setIsUpdatingStatus(false);
    }
  };

  return (
    <div className="bom-detail-container">
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      
      <div className="bom-detail-header">
        <div className="bom-detail-tabs">
          <div 
            className={`bom-detail-tab ${activeTab === 'detail' ? 'active' : ''}`}
            onClick={() => handleTabChange('detail')}
          >
            BOM详情
          </div>
          <div 
            className={`bom-detail-tab ${activeTab === 'list' ? 'active' : ''}`}
            onClick={() => handleTabChange('list')}
          >
            BOM列表
          </div>
          <div style={{ flex: 1 }}></div>
            <Button 
              icon={<EditOutlined />} 
            style={{ margin: '8px 0' }}
              onClick={checkBOMEditStatus}
            >
              编辑
            </Button>
        </div>
      </div>
      
      <Spin spinning={loading && activeTab === 'detail'}>
        <div className="bom-detail-content">
          {activeTab === 'detail' ? renderBOMDetail() : renderBOMList()}
        </div>
      </Spin>

      {/* BOM状态编辑模态框 */}
      <Modal
        title="修改产品BOM状态"
        open={editModalVisible}
        onOk={handleEditConfirm}
        onCancel={handleEditCancel}
        confirmLoading={isUpdatingStatus}
        maskClosable={false}
      >
        <p>确认将产品BOM状态修改为"发布"吗？</p>
        <p>状态修改为发布后将无法再次编辑。</p>
      </Modal>
    </div>
  );
};

// 导出组件
export { ProductBOM as default, BOMDetail }; 